# -*- coding: utf-8 -*-
# @Time    : 2018/12/23/023 22:58
# @Author  : 山那边的瘦子
# @Email   : 690238539@qq.com
# @File    : tasks.py

from celery import Celery
from flask import Flask

import schedule
import time

from config import Config

from spiders.spider import Spider

app = Flask(__name__)
app.config.from_object(Config)


def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery


celery = make_celery(app)


def spider():
    ips = Spider()  # 可传递传输 page 页数
    ips.run()


@celery.task
def get_ips():
    schedule.every().minute.do(spider)
    # schedule.every(10).minutes.do(spider)
    # schedule.every().hour.do(job)
    # schedule.every().day.at("10:30").do(job)
    # schedule.every(5).to(10).days.do(job)
    # schedule.every().monday.do(job)
    # schedule.every().wednesday.at("13:15").do(job)

    while True:
        schedule.run_pending()
        time.sleep(1)
